import { ref, watch, watchEffect } from 'vue'
import { Field, Table } from '../moduleDetailType'
import { formRequiredIsFilled } from '@/utils'
import { ElMessageBox } from 'element-plus'

export default function useFieldMethods () {
  const fieldFormRef = ref()
  const fieldList = ref<Array<Field>>([])
  const fieldItemActive = ref(-1)
  const formDataField = ref<Field>({
    id: 0,
    name: '',
    aliasName: '',
    primaryKey: false,
    comment: '',
    charset: 'utf8mb4',
    collate: 'utf8mb4_0900_ai_ci',
    defaultValue: '',
    type: 'varchar',
    sort: 0,
    required: false,
    maxLength: 255,
    updateByCurrentTime: false,
    decimalDigits: 2
  })
  const fieldFormRules = {
    name: [{ required: true, message: '请输入字段名', trigger: 'blur' }],
    aliasName: [{ required: true, message: '请输入别名', trigger: 'blur' }],
    type: [{ required: true, message: '请选择类型', trigger: 'change' }],
    sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
    maxLength: [{ required: true, message: '请输入最大长度', trigger: 'blur' }],
    // decimalDigits:[{ required: true, message: '请输入小数位数', trigger: 'blur' }]
  } as any

  function resetFieldForm () {
    formDataField.value = {
      id: 0,
      name: '',
      aliasName: '',
      primaryKey: false,
      comment: '',
      charset: 'utf8mb4',
      collate: 'utf8mb4_0900_ai_ci',
      defaultValue: '',
      type: 'varchar',
      sort: 0,
      required: false,
      maxLength: 255,
      decimalDigits: 2,
    }
  }
  /**
   * 选择字段项
   *
   * @param item 要选择的字段项对象
   */
  function selectFieldItem (from: number, item: any,) {
    fieldFormRef.value && fieldFormRef.value.validate()
    
    let isFilled = formRequiredIsFilled(fieldFormRules, formDataField.value)
    if (!isFilled && from != -1) {
      return
    } else {
      fieldItemActive.value = item.id
      formDataField.value = item
    }
  }

  /**
   * 对字段进行排序
   *
   * @param item 需要排序的字段对象
   * @param order 排序顺序，1 表示升序，-1 表示降序
   */
  function orderField (item: any, order: number) {
    if (order == 1) {
      fieldList.value[item.sort + 1].sort -= 1
    }
    if (order == -1) {
      fieldList.value[item.sort - 1].sort += 1
    }
    item.sort = item.sort + order
    fieldList.value = fieldList.value.sort((a, b) => {
      return a.sort - b.sort
    })
  }

  const reWriteMessageVisible = ref(false)
  const fieldInputNameRef = ref()
  /**
   * 校验输入字段名称是否重复
   *
   * 遍历字段列表，检查是否存在与当前表单字段名称相同但ID不同的字段。
   * 如果存在，则显示重新编写消息的提示框。
   */
  function inputFieldName () {
    //检验是否有相同的字段名
    fieldList.value.forEach(item => {
      if (
        item.name == formDataField.value.name &&
        item.id != formDataField.value.id
      ) {
        reWriteMessageVisible.value = true
      }
    })
  }

  /**
   * 重写消息弹窗回调
   *
   * 该函数用于重置重写消息的状态，并将输入框聚焦。
   */
  function reWriteMessage () {
    reWriteMessageVisible.value = false
    fieldInputNameRef.value!.focus()
  }

  function deleteField (item: any) {
    ElMessageBox.confirm('确定删除该字段吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        if (item.id == fieldItemActive.value) {
          fieldItemActive.value = -1
          resetFieldForm()
        }
        fieldList.value = fieldList.value.filter(i => i.id !== item.id)
        // 删除之后自动选择上一个field
        if (fieldList.value.length > 0) {
          fieldItemActive.value = fieldList.value[fieldList.value.length - 1].id
        }
      })
      .catch(() => {
        // 取消删除
      })
  }

  /**
   * 添加一个新的字段到字段列表中
   */
  function addField () {
    let m = new Date().getTime()
    if (fieldList.value.length == 0 || !fieldFormRef.value) {
      fieldList.value.push({
        id: m,
        name: 'field' + m,
        aliasName: 'FIELD' + m,
        primaryKey: false,
        comment: '',
        charset: 'utf8mb4',
        collate: 'utf8mb4_0900_ai_ci',
        defaultValue: '',
        type: '',
        sort: fieldList.value.length,
        required: false,
        maxLength: 255,
        decimalDigits: 2
      })
      fieldItemActive.value = m // 激活最新的表单项
      formDataField.value = fieldList.value[fieldList.value.length - 1]
    } else {
      fieldFormRef.value && fieldFormRef.value.validate()
      //  先验证当前表单是否已经填写完成
      let isFilled = formRequiredIsFilled(fieldFormRules, formDataField.value)
      if (isFilled) {
        let m = new Date().getTime()
        fieldList.value.push({
          id: m,
          name: 'field' + m,
          aliasName: 'FIELD' + m,
          primaryKey: false,
          comment: '',
          charset: 'utf8mb4',
          collate: 'utf8mb4_0900_ai_ci',
          defaultValue: '',
          type: '',
          sort: fieldList.value.length,
          required: false,
          maxLength: 255,
          decimalDigits: 2
        })
        fieldItemActive.value = m // 激活最新的表单项
        formDataField.value = fieldList.value[fieldList.value.length - 1]
      }
    }
  }
  const fieldActiveIndex = ref(0)
  watch(
    () => fieldItemActive.value,
    (val: any) => {
      fieldActiveIndex.value = fieldList.value.findIndex(i => i.id == val)
      let a = fieldList.value[fieldActiveIndex.value]
      if (a) {
        formDataField.value = a
      }
    },
    {
      immediate: true
    }
  )

  return {
    fieldList,
    fieldItemActive,
    formDataField,
    selectFieldItem,
    orderField,
    reWriteMessageVisible,
    inputFieldName,
    deleteField,
    addField,
    fieldFormRef,
    fieldInputNameRef,
    reWriteMessage,
    fieldFormRules,
    resetFieldForm
  }
}
